//
//  M4BaseViewController.swift
//  M4
//
//  Created by YuChuang on 2024/8/6.
//

import UIKit

protocol M4BaseTableViewCellProtocol: NSObject {
    func M4CellAction(_ action: M4IDAction)
}


class M4BaseViewController: UIViewController, M4BaseTableViewCellProtocol {
    
    private var M4BackButton: UIButton?
    
    private var M4BackImage: UIImageView = UIImageView()
    
    var inTime: Int = Int(Date().timeIntervalSince1970 * 1000) 
    
    var M4BackIcon: String = "icon_back_white" {
        didSet {
            M4BackImage.image = UIImage(named: M4BackIcon)
//            M4BackButton?.setImage(UIImage(named: M4BackIcon), for: .normal)
        }
    }
    
    var M4NeedLeft: Bool = true {
        didSet {
            M4BackButton?.isHidden = !M4NeedLeft
        }
    }
    
    var showSuggentionViewButton = false
    
    lazy var lineView: UIView = {
        let line = UIView()
        line.backgroundColor = COLOR_EEEEEE
        return line
    }()
    
//    var M4IsInfosPage: Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = COLOR_F1F3F5
        M4NavBarColor = COLOR_00479D
        if M4NeedLeft {
            M4NavLeftItem()
        }
    }
    
    var M4NavBarColor: UIColor = COLOR_00479D {
        didSet{
            if #available(iOS 13.0, *) {
                let appearance = UINavigationBarAppearance()
                appearance.backgroundColor = M4NavBarColor
                appearance.shadowColor = nil
                self.navigationController?.navigationBar.standardAppearance = appearance
                self.navigationController?.navigationBar.scrollEdgeAppearance = appearance
            }
            else {
                // Fallback on earlier versions
                UINavigationBar.appearance().barTintColor = M4NavBarColor
            }
            if M4NavBarColor == UIColor.white {
                self.view.addSubview(lineView)
                lineView.snp.makeConstraints { make in
                    make.top.equalToSuperview().offset(M4NavigationFullHeight())
                    make.left.right.equalToSuperview()
                    make.height.equalTo(0.5)
                }
            }
        }
    }
    
    func M4NavTitle(M4Title: String, M4NavTitleColor:UIColor = UIColor.white) {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 16, weight: .regular)
        label.text = M4Title
        label.textColor = M4NavTitleColor
        navigationItem.titleView = label
    }

    func M4NavLeftItem() {
        M4BackButton = UIButton(type: .custom)
        M4BackButton?.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
        M4BackButton?.setTitle("", for: .normal)
        M4BackImage.image = UIImage(named: M4BackIcon)
        M4BackButton?.addSubview(M4BackImage)
        M4BackImage.snp.makeConstraints { make in
            make.leading.centerY.equalToSuperview()
            make.width.equalTo(9)
            make.height.equalTo(17)
        }
        M4BackButton?.addTarget(self, action: #selector(M4BackClick(sender:)), for: .touchUpInside)
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: M4BackButton ?? UIButton())
    }
    
    func M4NavRightItem() {
        let btn = UIButton(type: .custom)
        btn.frame = CGRect(x: 0, y: 0, width: 36, height: 36)
        btn.setTitle("", for: .normal)
        btn.setImage(UIImage(named: "icon_cs"), for: .normal)
        btn.addTarget(self, action: #selector(M4ServiceClick(sender:)), for: .touchUpInside)
        
        
        let suggestionButton = UIButton(type: .custom)
        suggestionButton.setBackgroundImage(UIImage(named: "icon_suggenstion_gray"), for: .normal)
        suggestionButton.setTitle("", for: .normal)
        suggestionButton.addTarget(self, action: #selector(M4ToSuggestionView(_:)), for: .touchUpInside)
        
        if showSuggentionViewButton == true {
            navigationItem.rightBarButtonItems = [
                UIBarButtonItem(customView: btn),
                UIBarButtonItem(customView: suggestionButton),
            ]
        } else {
            navigationItem.rightBarButtonItem = UIBarButtonItem(customView: btn)
        }
    }
    
    @objc func M4ToSuggestionView(_ sender: UIButton) {
        self.navigationController?.pushViewController(M4SuggestionViewController(), animated: true)
        sender.M4EventUnavailable = false
    }
    
    lazy var M4TableView: UITableView = {
        let table = UITableView.init(frame: CGRect.zero, style: M4tableStyle())
        table.backgroundColor = UIColor.clear
        table.tableFooterView = UIView.init(frame: CGRect.zero)
        table.tableHeaderView = UIView.init(frame: CGRect.zero)
        table.showsHorizontalScrollIndicator = false
        table.showsVerticalScrollIndicator = false
        table.delegate = self
        table.dataSource = self
        table.rowHeight = UITableView.automaticDimension
        table.estimatedRowHeight = 980
        table.separatorStyle = .none
        if #available(iOS 15.0, *) {
            table.sectionHeaderTopPadding = 0
        }
        // ✅ 关键修复
           if #available(iOS 11.0, *) {
               table.contentInsetAdjustmentBehavior = .never
           }
//        self.view.addSubview(table)
        return table
    }()

    public var M4TableSources: [M4TableViewCellData] = []
    
//    func M4ConfigTableView() {
//        self.view.addSubview(M4TableView)
//    }
    
    func M4CellAction(_ action: M4IDAction) {
        
    }
    
    func M4DataRefresh() {
        
    }

}

extension M4BaseViewController {
    
    func M4InfosPageBack() {
        let alert = UINib(nibName: "M4InfosBackAlertView", bundle: nil).instantiate(withOwner: self).last as! M4InfosBackAlertView
        alert.M4QuitBlock = {
            if self.navigationController?.viewControllers.first is M4CrediteInfoViewController ||
                self.navigationController?.viewControllers.first is M4FirstInfoViewController {
                AppDelegate.keyWindow()?.rootViewController = M4TabBarViewController()
            }
            else {
                self.navigationController?.popToRootViewController(animated: true)
            }
            M4DeviceDataManager.m4DeviceShare.m4MQtjG = 1
        }
        alert.M4AlertViewShow()
    }
    
    @objc func M4BackClick(sender: UIButton) {
        if (self.presentingViewController != nil && self.navigationController?.viewControllers.count == 1) {
            self.dismiss(animated: true)
        } else {
            self.navigationController?.popViewController(animated: true)
        }
        sender.M4EventUnavailable = false
    }
    
    @objc func M4ServiceClick(sender: UIButton) {
        self.view.endEditing(true)
        let alert = M4KFAlertView()
        alert.didTapKFzxHandle = {
            
            
        }
        alert.M4AlertViewShow()
        sender.M4EventUnavailable = false
    }
    
    static func M4CurrentVC() -> M4BaseViewController? {
        if let tabbarController = (UIApplication.shared.delegate as! AppDelegate).window?.rootViewController as? UITabBarController {
            guard let navController = tabbarController.viewControllers?[tabbarController.selectedIndex] as? UINavigationController else { return nil }
            guard let vC = navController.viewControllers.last as? M4BaseViewController else { return nil }
            return vC
        }
        else {
            guard let rootVC = (UIApplication.shared.delegate as! AppDelegate).window?.rootViewController as? M4BaseViewController else { return nil }
            return rootVC
        }
    }
    
}
